<?php

namespace Yolo\Utils;

/**
 * Array utility class.
 * @date 2025-01-23
 */
class Arr
{
    /**
     * Pick an array of keys from another array.
     * @param array $array The array to pick from.
     * @param array $keys The keys to pick.
     * @param bool $ignoreMissing Whether to ignore missing keys.
     * @return array The picked array.
     */
    public static function pick(array $array, array $keys, bool $ignoreMissing = true): array
    {
        $result = [];

        foreach ($keys as $key) {
            if (array_key_exists($key, $array)) {
                $result[$key] = $array[$key];
            } elseif (!$ignoreMissing) {
                $result[$key] = null;
            }
        }

        return $result;
    }

    /**
     * @param array $array
     * @param int $level
     * @return string
     */
    public static function arrayToString(array $array, int $level = 1): string
    {
        $indent = str_repeat('    ', $level); // 缩进
        $result = "[\n";
        $items = [];

        foreach ($array as $key => $value) {
            $line = $indent . var_export($key, true) . ' => ';
            if (is_array($value)) {
                $line .= self::arrayToString($value, $level + 1);
            } else {
                $line .= var_export($value, true);
            }
            $items[] = $line;
        }

        $result .= implode(",\n", $items) . "\n" . str_repeat('    ', $level - 1) . "]";
        return $result;
    }
}
